import { Configuration } from './generated/runtime';
import { CONFIG } from '@/constants/config';
import {
  TokenApi,
  AccountsApi,
  AuthApi,
  NavigationApi,
} from './generated/apis';
import { refreshToken } from './auth';
import { message } from 'antd';

// 处理错误消息
interface ApiError extends Error {
  response?: any;
}

const handleErrorMessage = (error: ApiError) => {
  if (error.response) {
    const status = error.response.status;
    const data = error.response.data;

    if (status === 401) {
      if (data?.detail === '只有工作人员可以登录系统') {
        message.error('只有工作人员可以登录系统');
      } else if (data?.detail === '当前密码不正确') {
        message.error('当前密码不正确');
      } else if (data?.detail) {
        message.error(data.detail);
      } else {
        message.error('认证失败');
      }
    } else if (status === 400) {
      if (data?.non_field_errors) {
        message.error(data.non_field_errors[0]);
      } else if (data?.detail) {
        message.error(data.detail);
      } else if (data?.old_password) {
        message.error(data.old_password[0]);
      } else if (data?.new_password) {
        message.error(data.new_password[0]);
      } else {
        const firstError = Object.values(data)[0];
        if (Array.isArray(firstError)) {
          message.error(firstError[0]);
        } else {
          message.error('请求参数错误');
        }
      }
    } else if (status === 403) {
      message.error('没有权限执行此操作');
    } else if (status === 404) {
      message.error('请求的资源不存在');
    } else if (status === 500) {
      message.error('服务器内部错误');
    } else {
      message.error('请求失败，请稍后重试');
    }
  } else if (error.request) {
    message.error('网络请求失败，请检查网络连接');
  } else {
    message.error('请求出错，请稍后重试');
  }
};

// API 配置
export const apiConfig = new Configuration({
  basePath: CONFIG.API.BASE_URL,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  },
  credentials: 'include',
  middleware: [
    {
      pre: async (context: any) => {
        const token = localStorage.getItem(CONFIG.CACHE.TOKEN_KEY);
        if (token) {
          context.init.headers = {
            ...context.init.headers,
            Authorization: `Bearer ${token}`,
          };
        }
        return context;
      },
      post: async (context: any) => {
        try {
          const response = context.response.clone();
          
          if (!response.ok) {
            if (response.status === 401) {
              try {
                const newToken = await refreshToken();
                // 使用新token重试请求
                const retryContext = {
                  ...context,
                  init: {
                    ...context.init,
                    headers: {
                      ...context.init.headers,
                      Authorization: `Bearer ${newToken}`,
                    },
                  },
                };
                return fetch(context.url, retryContext.init);
              } catch (error) {
                // 刷新token失败，清除认证信息并重定向到登录页
                localStorage.removeItem(CONFIG.CACHE.TOKEN_KEY);
                localStorage.removeItem(CONFIG.CACHE.REFRESH_TOKEN_KEY);
                localStorage.removeItem(CONFIG.CACHE.DEVICE_ID_KEY);
                localStorage.removeItem(CONFIG.CACHE.USER_INFO_KEY);
                
                // 如果不是登录页面，则重定向
                if (window.location.pathname !== '/login') {
                  window.location.href = '/login';
                }
                throw error;
              }
            }
            
            // 处理错误消息
            const error: ApiError = {
              response: response,
              name: 'ApiError',
              message: response?.statusText || 'An API error occurred'
            };
            handleErrorMessage(error);
            throw error;
          }
          
          return context.response;
        } catch (error) {
          handleErrorMessage(error);
          throw error;
        }
      },
    },
  ],
});

// API 实例
export const api = {
  token: new TokenApi(apiConfig),
  accounts: new AccountsApi(apiConfig),
  auth: new AuthApi(apiConfig),
  navigation: new NavigationApi(apiConfig),
};
